const MongoClient = require('mongodb').MongoClient;
const moment = require('moment');
const config = require('../config.js');
const logs = require('./logs.js');
let db;
var mongodb = {};

MongoClient.connect(config.mongodb_url, {useNewUrlParser: true, useUnifiedTopology: true }, async function(err, client) {
	//logs.logvar(err, client);

	db = client.db(config.mongodb_db);
	let ret = await db.collection('users').find().limit(1).toArray();
	//logs.logvar(ret);
	if(ret.length == 0){
		await create_mongodb_index(db);
	}
});

function mongo_foreach(fun){
	['users'].forEach((item, index)=>{
		fun(item, index);
	})
}

async function create_mongodb_index(db){
	try{
		await db.collection('users').createIndex( { id: 1 }, {unique: true});
		await db.collection('devices').createIndex( { device_id: 1 }, {unique: true});

		logs.logvar('create_mongodb_index');
	}catch (e) {
		logs.logvar(e);
	}
}

mongodb.insert = async function (data) {
	console.log('data:', data);
	logs.logvar(data, typeof (data));
	const ret = await db.collection('users', {safe:true}).insertOne(data);

	//logs.logvar(ret);
	return ret;
}

mongodb.login = async function (data) {
	logs.logvar(data, typeof (data));
	const ret = await db.collection('users').find({id:data.id, password:data.password}).toArray();
	logs.logvar(ret);

	if(ret.length == 0){
		throw  Error('验证用户登陆失败');
	}

	return ret[0];
}

mongodb.search = async function (data) {
	logs.logvar(data, typeof (data));
	const ret = await db.collection('users').find(data).toArray();

	return ret.map(it=>{ delete it.password; delete it._id; return it;});
}

/*****************
 * 注册设备
 */
mongodb.add = async function (data) {
	logs.logvar(data, typeof (data));

	if(data.device_id == null || data.device_password == null){
		throw  Error(`数据格式错误！`);
	}

	const ret = await db.collection('devices', {safe:true}).insertOne(data);
	//logs.logvar(ret);
	return true;
}

/*****************
 * 添加设备
 */
mongodb.add_device = async function (data) {
	logs.logvar(data, typeof (data));

	const user = await mongodb.login(data);
	if(user.devices == null){
		user.devices = {};
	}

	for(let i = 0; i < data.devices.length; i++){
		let dev = data.devices[i];
		const ret = await db.collection('devices').find({device_id:dev.device_id});
		if(typeof (dev.device_id) == "undefined"){
			throw  Error(`数据格式错误！`);
		}
		if(ret.length == 0){
			throw  Error(`设备${dev.device_id}不存在`);
		}

		dev.add_time = moment().format("YYYY-MM-DD HH:mm:ss");
		dev.expire_time = moment().add(3, "years").format("YYYY-MM-DD HH:mm:ss");

		user.devices[dev.device_id] = dev;
	}

	logs.logvar(user);
	const ret = await db.collection('users', {safe:true}).update({id:user.id}, user);
	//logs.logvar(ret);

	return true;
}

/*****************
 * 删除设备
 */
mongodb.del_device = async function (data) {
	logs.logvar(data, typeof (data));

	const user = await mongodb.login(data);
	if(user.devices == null){
		return;
	}

	for(let i = 0; i < data.devices.length; i++){
		delete user.devices[data.devices[i]]
	}

	logs.logvar(user);
	const ret = await db.collection('users', {safe:true}).update({id:user.id}, user);
	//logs.logvar(ret);

	return true;
}

module.exports = mongodb;

